const { join } = require('path')
const Executor = require('../Executor')
const { Worker } = require('worker_threads')

class WorkerExecutor extends Executor {
    #worker
    async onInit() {
        const modulePath = join(__dirname, 'WorkerExecutorLoder.js')
        const worker = new Worker(modulePath, {
            workerData: {
                logPath: this.logPath,
                logFile: this.logFile
            },
            name: this.name
        })
        worker.on('message', this.on.bind(this))
        worker.on('exit', this.close.bind(this))
        this.#worker = worker
        this.disposable.push(() => {
            worker.terminate()
        })
        this.logger?.info('创建线程成功, 线程: %s', worker.threadId)
    }
    async onSend(data) {
        this.#worker.postMessage(data)
    }
}

module.exports = WorkerExecutor
